package lessons.no7;

import java.io.FileReader;
import java.io.FileWriter;

/***
 * 文件的读写
 */
public class MyFile {
    
    public static void main(String[] args) throws Exception{
        
        //System.out.println("test.txt 文件内容:"+MyFile.read("test.txt"));

        MyFile.write("test.txt", "123456789");
    }
    /**
     * 从文件读取数据
     * @param filename 文件名
     * @return
     */
    static public String read(String filename) throws Exception
    {
        FileReader fileReader = new FileReader(filename);
        String msg="";
        char[] buff = new char[1024];
        int len=0;
        while((len = fileReader.read(buff)) != -1)
        {
            String str = new String(buff);
            msg+=str;
        }

        fileReader.close();
        return msg;
        
    }

    /**
     * 从文件写入数据
     * @param filename 文件名
     * @param str 数据
     */
    static public void write(String filename,String str)throws Exception
    {
        FileWriter fileWriter = new FileWriter(filename);
        fileWriter.write(str);
        fileWriter.close();
    }
}
